#include "serial.h"
#include "ui_serial.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QTextCursor>  // ← 新增：用于滚动

serial::serial(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::serial),
    m_serial(new QSerialPort(this))
{
    ui->setupUi(this);
    setWindowTitle("串口助手");

    // 填充可用串口
    for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()) {
        ui->portComboBox->addItem(info.portName());
    }

    // 填充波特率
    ui->baudComboBox->addItems({"9600", "19200", "38400", "57600", "115200"});
    ui->baudComboBox->setCurrentText("115200");

    // 默认发送内容
    ui->sendEdit->setText("ai300");

    // 初始状态
    ui->statusLabel->setText("状态：未连接");

    // 连接串口数据接收信号
    connect(m_serial, &QSerialPort::readyRead, this, &serial::readSerialData);
}

serial::~serial()
{
    delete ui;
}

void serial::on_openButton_clicked()
{
    if (m_serial->isOpen()) {
        m_serial->close();
        ui->openButton->setText("打开串口");
        ui->statusLabel->setText("状态：已关闭");
    } else {
        QString portName = ui->portComboBox->currentText();
        if (portName.isEmpty()) {
            QMessageBox::warning(this, "错误", "没有可用串口！");
            return;
        }

        m_serial->setPortName(portName);
        m_serial->setBaudRate(ui->baudComboBox->currentText().toInt());
        m_serial->setDataBits(QSerialPort::Data8);
        m_serial->setParity(QSerialPort::NoParity);
        m_serial->setStopBits(QSerialPort::OneStop);
        m_serial->setFlowControl(QSerialPort::NoFlowControl);

        // 关键：必须用 ReadWrite 才能接收数据！
        if (m_serial->open(QIODevice::ReadWrite)) {
            ui->openButton->setText("关闭串口");
            ui->statusLabel->setText("状态：已连接 " + portName);
            ui->receiveEdit->clear(); // 清空接收区
        } else {
            QMessageBox::critical(this, "错误", "无法打开串口:\n" + m_serial->errorString());
        }
    }
}

void serial::on_sendButton_clicked()
{
    if (!m_serial->isOpen()) {
        QMessageBox::warning(this, "提示", "请先打开串口！");
        return;
    }

    QString text = ui->sendEdit->text().trimmed();
    if (text.isEmpty()) {
        QMessageBox::warning(this, "提示", "发送内容不能为空！");
        return;
    }

    m_serial->write(text.toUtf8());
    ui->statusLabel->setText("状态：已发送 \"" + text + "\"");
}

void serial::readSerialData()
{
    // 读取所有可用数据
    QByteArray data = m_serial->readAll();
    if (!data.isEmpty()) {
        QString text = QString::fromUtf8(data);

        // 追加到接收区并滚动到底部
        ui->receiveEdit->moveCursor(QTextCursor::End);
        ui->receiveEdit->insertPlainText(text);
        ui->receiveEdit->moveCursor(QTextCursor::End);
    }
}
